<template>
	<view class="wrap">
		<view class="content">
			<view class="title">欢迎登录航院闲鱼</view>
			
			<u-tabs :list="tabsList" :is-scroll="false" :current="tabsCurrent" @change="tabsChange"></u-tabs>
			<u-form :model="form" :rules="rules" ref="uForm" v-if="tabsCurrent == 0">

				<u-form-item label="手机号" prop="phonenumber" label-width="150">
					<u-input type="number" v-model="form.phonenumber" maxlength="11" placeholder="请输入手机号" />
				</u-form-item>
				
				<u-form-item v-if="loginType == 1" label="密码" prop="password" label-width="150">
					<u-input type="password" v-model="form.password" maxlength="20" placeholder="请输入密码" />
				</u-form-item>

				<u-form-item v-if="loginType == 2" label="验证码" prop="code" label-width="150">
					<u-input type="number" v-model="form.code" maxlength="6" placeholder="请输入验证码" />
					<u-button slot="right" type="primary" size="mini" @click="getCode">{{codeTips}}</u-button>
				</u-form-item>
				
				<button @click="login()" v-if="loginType == 1" :style="[inputStyle]" class="loginButton">登录</button>
				<button @click="loginByVerificationCode()" v-if="loginType == 2" :style="[inputStyle]" class="loginButton">登录</button>
			</u-form>

			<view class="alternative" v-if="tabsCurrent == 0">
				<view class="login-type" @click="loginTypeChange">{{loginTypeText}}</view>
				<view class="issue">遇到问题</view>
			</view>
			
			<u-form :model="form" :rules="rules" ref="uForm" v-if="tabsCurrent == 1">
			
				<u-form-item label="手机号" prop="phonenumber" label-width="150">
					<u-input type="number" v-model="form.phonenumber" maxlength="11" placeholder="请输入手机号" />
				</u-form-item>
				
				<u-form-item label="密码" prop="password" label-width="150">
					<u-input type="password" v-model="form.password" maxlength="20" placeholder="请输入密码" />
				</u-form-item>
				
				<u-form-item label="验证码" prop="code" label-width="150">
					<u-input type="number" v-model="form.code" maxlength="6" placeholder="请输入验证码" />
					<u-button slot="right" type="primary" size="mini" @click="getCode">{{codeTips}}</u-button>
				</u-form-item>

				<button @click="register()" :style="[inputStyle]" class="loginButton">注册</button>
				
			</u-form>
			
			<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
			
			<u-toast ref="uToast" />
			
		</view>
		
		<view class="auth-login-type">
			<view class="QQ item" @click="getUserByQQ()">
				<view class="icon">
					<u-icon size="70" name="qq-fill" color="rgb(17,183,233)"></u-icon>
				</view>
				QQ
			</view>
			<view class="wechat item" @click="getUserByWx()">
				<view class="icon">
					<u-icon size="70" name="weixin-fill" color="rgb(83,194,64)"></u-icon>
				</view>
				微信
			</view>
		</view>

		
		<view class="hint">
			登录代表同意
			<text class="link">航院闲鱼用户协议、隐私政策，</text>
			并授权使用您的航院闲鱼账号信息（如昵称、头像、收获地址）以便您统一管理
		</view>
	</view>
</template>

<script>
	import {
		register,
		login,
		sendCode,
		loginByVerificationCode,
		loginByWx,
		appLoginByQQ,
		appLoginByWx
	} from "@/api/login.js";
	import {
		constant
	} from '@/utils/constant.js'
	const app = getApp();
	export default {
		data() {
			return {
				tabsList: [{
					name: '登录'
				}, {
					name: '注册'
				}],
				tabsCurrent: 0, // 0登录，1注册
				codeTips: '',
				form: {
					phonenumber: '',
					code: '',
					password: ''
				},
				loginTypeText: '验证码登录',
				loginType: 1,
				params: {},
				rules: {
					phonenumber: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					code: [{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: ['change', 'blur'],
						},
						{
							min: 6,
							max: 20,
							message: '密码长度在6到20个字符',
							trigger: ['blur'],
						}
					]
				},
			}
		},
		computed: {
			inputStyle() {
				let style = {}
				style.color = "#fff";
				style.backgroundColor = this.$u.color['warning'];
				return style;
			}
		},
		methods: {
			// tabs通知swiper切换
			tabsChange(index) {
				this.tabsCurrent = index;
				this.form = {}
			},
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					let params = {}
					params.phonenumber = this.form.phonenumber
					if(this.tabsCurrent == 1) {
						params.type = "register"
					}
					sendCode(params).then(res => {
						// 这里此提示会被this.start()方法中的提示覆盖
						this.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			login() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let params = {}
						params.phonenumber = this.form.phonenumber
						params.password = this.form.password
						login(params).then(res => {
							//存储用户信息
							uni.setStorageSync(constant.userInfo, res.data
								.userInfo);
							uni.setStorageSync(constant.tokenKey, constant
								.tokenPrefix + res.data.token);
							app.globalData.userInfo = res.data.userInfo;
							app.globalData.token = res.data.token;
							
							uni.navigateBack({
								delta: 1,
								fail: (res) => {
									uni.switchTab({
										url: '/pages/user/user',
									})
								}
							})
						})
					} 
				});
			},
			loginByVerificationCode() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let params = this.form
						loginByVerificationCode(params).then(res => {
							//存储用户信息
							uni.setStorageSync(constant.userInfo, res.data
								.userInfo);
							uni.setStorageSync(constant.tokenKey, constant
								.tokenPrefix + res.data.token);
							app.globalData.userInfo = res.data.userInfo;
							app.globalData.token = res.data.token;
							
							uni.navigateBack({
								delta: 1,
								fail: (res) => {
									uni.switchTab({
										url: '/pages/user/user',
									})
								}
							})
						})
					}
				});
			},
			loginTypeChange() {
				if(this.loginType == 1) {
					this.loginType = 2
					this.loginTypeText = '密码登录'
				} else {
					this.loginType = 1
					this.loginTypeText = '验证码登录'
				} 
			},
			register() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let params = this.form
						register(params).then(res => {
							this.tabsChange(0)
							this.$refs.uToast.show({
								title: '注册成功，请登录',
								type: 'success'
							})
						})
					}
				});
			},
			// 获取用户信息
			getUserByQQ() {
				let that = this;

				// // #ifdef MP-WEIXIN
				// /**
				//  * 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				//  * 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				//  */
				// uni.getUserProfile({
				// 	desc: '获取你的昵称、头像、地区及性别',
				// 	success: (infoRes) => {
				// 		that.params = infoRes;

				// 		uni.login({
				// 			success: (loginRes) => {
				// 				console.log(loginRes)
				// 				if (loginRes.code) {
				// 					that.params.code = loginRes.code;

				// 					// 登录用户信息收集完成，开始登录后台服务器
				// 					// login(that.userInfo)
				// 					loginByWx(that.params).then(res => {
				// 						//存储用户信息
				// 						uni.setStorageSync(constant.userInfo, res.data.userInfo);
				// 						uni.setStorageSync(constant.tokenKey, constant.tokenPrefix + res.data.token);
				// 						app.globalData.userInfo = res.data.userInfo;
				// 						app.globalData.token = res.data.token;
				// 						that.userInfo = res.data.userInfo;
				// 						that.isAuthInfo = true;
				// 					})

				// 				}
				// 			}
				// 		})
				// 	}
				// })

				// // #endif

				// #ifdef APP-PLUS
				uni.login({
					provider: 'qq',
					success: (loginRes) => {
						console.log(loginRes)

						// 获取用户信息
						uni.getUserInfo({
							provider: 'qq',
							success: (infoRes) => {
								console.log(infoRes)
								that.params.avatarUrl = infoRes.userInfo.figureurl_qq
								that.params.nickName = infoRes.userInfo.nickname
								that.params.gender = infoRes.userInfo.gender_type
								that.params.city = infoRes.userInfo.city
								that.params.province = infoRes.userInfo.province
								that.params.openId = infoRes.userInfo.openId
								that.params.unionid = infoRes.userInfo.unionid
								appLoginByQQ(that.params).then(res => {
									//存储用户信息
									uni.setStorageSync(constant.userInfo, res.data
										.userInfo);
									uni.setStorageSync(constant.tokenKey, constant
										.tokenPrefix + res.data.token);
									app.globalData.userInfo = res.data.userInfo;
									app.globalData.token = res.data.token;

									uni.navigateBack({
										delta: 1,
										fail: (res) => {
											uni.switchTab({
												url: '/pages/user/user',
											})
										}
									})
								})
							}
						})
					}
				})
				// #endif
			},
			getUserByWx() {
				let that = this;
				// #ifdef APP-PLUS
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log(loginRes)

						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: (infoRes) => {
								console.log(infoRes)
								appLoginByWx(infoRes.userInfo).then(res => {
									//存储用户信息
									uni.setStorageSync(constant.userInfo, res.data
										.userInfo);
									uni.setStorageSync(constant.tokenKey, constant
										.tokenPrefix + res.data.token);
									app.globalData.userInfo = res.data.userInfo;
									app.globalData.token = res.data.token;

									uni.navigateBack({
										delta: 1,
										fail: (res) => {
											uni.switchTab({
												url: '/pages/user/user',
											})
										}
									})
								})
							}
						})
					}
				})
				// #endif
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	};
</script>

<style lang="scss" scoped>
	@import "./login.scss";
</style>
